package cn.net.isir.controller.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.net.isir.common.ResultObject;
import cn.net.isir.core.BasicController;
import cn.net.isir.core.SetBasicService;
import cn.net.isir.entity.Category;
import cn.net.isir.entity.Goods;
import cn.net.isir.service2.CategoryService;
import cn.net.isir.service2.GoodsService;
import cn.net.isir.utils.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author liuxubo
 * @filename CategoryController.java
 * @package cn.net.isir.controller.manager
 * @email lxb@isir.net.cn
 * @date 2018/12/04
 * @comment
 * @since 1.8
 */
@RestController
@RequestMapping("/category")
public class CategoryController extends BasicController<Category> {
    @SetBasicService
    @Resource
    private CategoryService categoryService;
    @Resource
    private GoodsService goodsService;

    /**
     * 根据用户id查询信息
     *
     * @param category userid放在
     * @return 列表
     */
    @Override
    public ResultObject selectListByUser(Category category) {
        try {
            if (StringUtils.isNotBlank(category.getName())) {
                category.setName(URLDecoder.decode(category.getName(), StandardCharsets.UTF_8.name()));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return super.selectListByUser(category);
    }

    /**
     * 增加信息
     *
     * @param map 增加信息
     * @return 结果
     */
    @Override
    public ResultObject add(@RequestBody Map map) {
        Category category = JSONObject.parseObject(JSON.toJSONString(map), Category.class);
        // 排序
        categoryService.reSort(category);
        return super.add(map);
    }

    /**
     * 保存修改信息
     *
     * @param map 信息实体类
     * @return 结果
     */
    @Override
    public ResultObject edit(@RequestBody Map map) {
        Category category = JSONObject.parseObject(JSON.toJSONString(map), Category.class);
        // 排序
        categoryService.reSort(category);
        return super.edit(map);
    }

    /**
     * 删除信息
     *
     * @param id 主键
     * @return 结果
     */
    @Override
    public ResultObject delete(@PathVariable String id) {
        Goods goods = new Goods();
        goods.setCategoryId(id);
        int count = goodsService.selectCount(goods);
        if (count > 0) {
            return new ResultObject(503, "fail", count);
        }
        categoryService.reSort(id);
        return super.delete(id);
    }
}
